package com.mzydz.nswitch;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;
import java.util.logging.Handler;

/**
 * Created by xiong on 2017-12-17.
 */

public class SwitchOrderManager implements Runnable{
    private Socket socket;
    private String ipAdress;
    private short port;
    private DataOutputStream out;

    public SwitchOrderManager(String ipAdress, short port){
        this.ipAdress = ipAdress;
        this.port = port;
    }

    public void setSwitch(int num, boolean isOpen){
        try {
            if(isOpen){
                out.writeUTF(String.format("AT+STACH%d=1", num));
            }else{
                out.writeUTF(String.format("AT+STACH%d=0", num));
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void disconnectSwitch(){

    }

    @Override
    public void run() {
            Socket socket = null;
            try {
                //创建一个流套接字并将其连接到指定主机上的指定端口号
                socket = new Socket(ipAdress, port);

                //读取服务器端数据
                DataInputStream input = new DataInputStream(socket.getInputStream());
                //向服务器端发送数据
                out = new DataOutputStream(socket.getOutputStream());

                while (true) {
                    String ret = input.readUTF();
                    if ("OK".equals(ret)) {
                        System.out.println("客户端将关闭连接");
                        Thread.sleep(500);
                        break;
                    }
                }

                out.close();
                input.close();
            } catch (Exception e) {
            } finally {
                if (socket != null) {
                    try {
                        socket.close();
                    } catch (IOException e) {
                        socket = null;
                    }
                }
            }
    }
}
